﻿using Framework.Components;
using Framework.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

/// <summary>
/// CMD服务
/// </summary>
namespace CmdService
{
    public partial class CmdService : ServiceBase
    {
        public CmdService()
        {
            InitializeComponent();
        }
        
        protected override void OnStart(string[] args)
        {
            var exePath = AppDomain.CurrentDomain.BaseDirectory; //启动程序路径
            Log.Info("服务启动: " + ServiceName + " " + exePath + " args: " + StringUtils.ToString(args));
            try
            {
                CmdProgresss.Instance.Start();
            }
            catch(Exception e)
            {
                Log.Error("服务启动错误: ", e);
                Stop(); // 这个是触发关闭, 不能在onStop中调用.
            }
        }

        protected override void OnStop()
        {
            try
            {
                Log.Info("服务停止");
                CmdProgresss.Instance.Stop();
            }
            catch (Exception e)
            {
                Log.Error("服务停止错误: ", e);
            }
        }

        protected override void OnShutdown()
        {
            Log.Info("电脑关闭触发");
            try
            {
                CmdProgresss.Instance.Stop();
                Log.Info("电脑关闭完成");
            }
            catch (Exception e)
            {
                Log.Error("电脑关闭错误: ", e);
            }
        }

        /// <summary>
        /// 服务暂停
        /// </summary>
        protected override void OnPause()
        {
            base.OnPause();
        }

        /// <summary>
        /// 服务继续
        /// </summary>
        protected override void OnContinue()
        {
            base.OnContinue();
        }

        /// <summary>
        /// 系统电源状态改变
        /// </summary>
        protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
        {
            return base.OnPowerEvent(powerStatus);
        }
    }
}
